import { Next, Request, Response } from "restify";

import { delAsync, getAsync, keysAsync, setExAsync } from "@src/lib/db/redis";

const REQUEST_CACHE_PREFIX = "REQ";

export const checkCache = (req: Request, res: Response, next: Next) => {
  getAsync(`${REQUEST_CACHE_PREFIX}_${req.href()}`)
    .then(result => {
      if (result !== null) {
        res.send(JSON.parse(result));
      } else {
        next();
      }
    })
    .catch(next);
};

export const updateCache = (req: Request, res: Response, next: Next) => {
  const data = (res as any)._data;
  const expireSeconds = 300;
  setExAsync(`${REQUEST_CACHE_PREFIX}_${req.href()}`, expireSeconds, data)
    .then(() => {
      next();
    })
    .catch(next);
};

export const invalidateCache = (prefix: string) => {
  return (req: Request, res: Response, next: Next) => {
    const inline = async (keys: string[]) => {
      for (const key of keys) {
        await delAsync(key);
      }
      next();
    };

    keysAsync(`${REQUEST_CACHE_PREFIX}_${prefix}*`)
      .then(inline)
      .catch(next);
  };
};
